/**
 * 
 */
package com.wbcs.jbsf.auth.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wbcs.jbsf.modal.abs.AbsRowModal;
import com.wbcs.jbsf.modal.abs.AbsTableModal;
import com.wbcs.jbsf.modal.abs.AbsTableSpaceModal;
import com.wbcs.jbsf.util.Consts;
import com.wbcs.jbsf.util.Server2Client;
import com.wbcs.jbsf.util.Wbcs4JBSFUtil;

/**
 * JBSFSecurity中间件的总控制器，负责总控和资源安全过滤两方面的事情
 * @author hawkfly
 */
public class SecurityFilter implements Filter
{
    private String contextpath;
    /* (non-Javadoc)
     * @see javax.servlet.Filter#destroy(
     */
    public void destroy()
    {
        
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest arg0,ServletResponse arg1,FilterChain chain) throws IOException,ServletException
    {
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response = (HttpServletResponse)arg1;
        String servletPath=request.getServletPath();
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        //查看请求资源是否在权限列表范围内，不在返回无权限，断开向下请求
        Object httpAuthesObj = session.getAttribute(Consts.SESSION_HTTPAUTHES);
        if(httpAuthesObj == null)//未登录
            request.getRequestDispatcher("/webresources/pages/exception/nonauth.jsp").forward(request,response);
        AbsTableModal httpauthes = (AbsTableModal)httpAuthesObj;
        AbsRowModal rowModal = httpauthes.getRow(servletPath);
        if(rowModal == null)//无权限
            request.getRequestDispatcher("/webresources/pages/exception/nonauth.jsp").forward(request,response);
        //在则检测本资源是读权限还是写权限并初始化本页面菜单（对于html静态页面只会判断是否可读及初始菜单，对于JSP动态页面才可以控制其读写权限）
        Object allmenusObj = session.getAttribute(Consts.SESSION_HTTPMENUS);
        if(allmenusObj != null){//本页面有菜单
            AbsTableSpaceModal allmenus = (AbsTableSpaceModal)allmenusObj;
            AbsTableModal pagemenus = allmenus.getTable(servletPath);
            Wbcs4JBSFUtil.toclientPacket4TS(pagemenus.parseLst2Maplst("LOCATIONCODE"),new Server2Client(request, response));
        }
        chain.doFilter(request,response);
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig config) throws ServletException
    {
        contextpath = config.getServletContext().getContextPath();
    }
}

